let callbacks = []
let loaded = false

const dynamicLoadScript = (src, callback) => {
	const existingScript = document.getElementById(src)
	const cb = callback || function () { }

	if (!existingScript) {
		const script = document.createElement('script')
		script.src = src // src url for the third-party library being loaded.
		script.id = src
		document.body.appendChild(script)
		callbacks.push(cb)
		const onEnd = 'onload' in script ? stdOnEnd : ieOnEnd
		onEnd(script)
	}
	else {
		if (loaded) {
			cb();
		} else {
			callbacks.push(cb)
		}
	}

	function stdOnEnd(script) {
		script.onload = function () {
			loaded = true;
			// this.onload = null here is necessary
			// because even IE9 works not like others
			this.onerror = this.onload = null
			for (const cb of callbacks) {
				cb()
			}
			callbacks = null
		}
		script.onerror = function () {
			this.onerror = this.onload = null
		}
	}

	function ieOnEnd(script) {
		script.onreadystatechange = function () {
			if (this.readyState !== 'complete' && this.readyState !== 'loaded') return
			loaded = true;
			this.onreadystatechange = null
			for (const cb of callbacks) {
				cb() // there is no way to catch loading errors in IE8
			}
			callbacks = null
		}
	}
}

export default dynamicLoadScript
